//
//  PictureBrowserCell.swift
//  MicroBlog
//
//  Created by  NorthCity on 15/11/18.
//  Copyright © 2015年  NorthCity. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD
//MARK: - 协议
protocol PictureBrowserCellDelegate:NSObjectProtocol{
    func pictureBrowserCellDidClickImage()
}

 class PictureBrowserCell:UICollectionViewCell{
//    定义代理
    weak var pictureCellDelegate:PictureBrowserCellDelegate?
    //    属性
    var imageURL:NSURL?{
        didSet{
            guard let url = imageURL else{
                return
            }
            // 重置占位视图
            resertScrollView()
            //            缩略图座位占位视图
            let key = url.absoluteString
            let placeHolderImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            setPlaceHolder(placeHolderImage)
            imageView.sd_setImageWithURL(
                middleURL(url),
                placeholderImage: nil,
                options: [SDWebImageOptions.RefreshCached,SDWebImageOptions.RetryFailed],
                progress: { (current, total) -> Void in
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.placeHoler.progress = CGFloat(current) / CGFloat(total)
                    })
                }){ (image, _, _, _) -> Void in
                
                if image == nil {
                    SVProgressHUD.showErrorWithStatus("加载图片失败")
                    return
                }
                    self.placeHoler.hidden = true
                    self.setImagePosition(image)
            }
            
        }
    }
    
    
    //    构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //    设置界面
    private func setUpUI(){
//        1 添加控件
        addSubview(scrollView)
        scrollView.addSubview(imageView)
        var rect = bounds
//        2 设置位置
        rect.size.width -= 20
        scrollView.frame = rect
        scrollView.addSubview(placeHoler)
        
//        3 设置 scrollView 缩放
        prepareScrollView()
//        4 添加手势识别
        let tap = UITapGestureRecognizer(target: self, action: "tapImage")
        imageView.userInteractionEnabled = true
        imageView.addGestureRecognizer(tap)
    }
//    MARK: - 懒加载控件
    ///    懒加载 scrollView
    lazy var scrollView:UIScrollView = UIScrollView()
    ///    懒加载 imageView
    lazy var imageView:UIImageView = UIImageView()
    ///    占位图片
    private lazy var placeHoler:ProgressImageView = ProgressImageView()
    
    private func middleURL(url:NSURL)->NSURL{
        
        var urlString = url.absoluteString
        urlString = urlString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        return NSURL(string: urlString)!
    }
//    MARK: - 调整图片方法
/// 调整图片大小
    private func displaySize(image:UIImage)->CGSize{
        let w:CGFloat = UIScreen.mainScreen().bounds.width
        let h:CGFloat = image.size.height * w / image.size.width
        return CGSize(width: w, height: h)
    }
/// 调整图片位置
    private func setImagePosition(image:UIImage){
//         1 计算图片大小
        let size = displaySize(image)
          scrollView.contentSize = size
//         2 判断图像高度
        if size.height > scrollView.bounds.height{
            imageView.frame = CGRect(origin: CGPointZero, size:size)
        }else{
            let y = (UIScreen.mainScreen().bounds.height - size.height) * 0.5
            imageView.frame = CGRectMake(0, 0, size.width, size.height)
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom:0 , right: 0)
        }
    }
    private func prepareScrollView(){
        
        
        scrollView.delegate = self
        scrollView.maximumZoomScale = 2.0
        scrollView.minimumZoomScale = 0.5
        
    }
    private func resertScrollView(){
        imageView.transform = CGAffineTransformIdentity
        scrollView.contentInset =  UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    
    private func setPlaceHolder(image:UIImage?){
//        1> 显示图片
        placeHoler.hidden = false
//        2> 设置图片
        placeHoler.image = image
//        3> 设置大小
        placeHoler.sizeToFit()
//        4> 设置位置
        placeHoler.center = scrollView.center
    }
    @objc private func tapImage(){
        pictureCellDelegate?.pictureBrowserCellDidClickImage()
    }
    
}
//MARK: - 实现代理方法
extension PictureBrowserCell:UIScrollViewDelegate{
    
     /// 返回要缩放的视图
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
     /// 缩放完成后就会调用
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        var offSetX = (UIScreen.mainScreen().bounds.width - view!.frame.width) * 0.5
        var offSetY = (UIScreen.mainScreen().bounds.height - view!.frame.height) * 0.5
        offSetX = (offSetX > 0 ? offSetY : 0)
        offSetY = (offSetY > 0 ? offSetY : 0)
        scrollView.contentInset = UIEdgeInsets(top: offSetY, left: offSetX, bottom: 0, right: 0)
    }
     /// 只要缩放就会调用
    func scrollViewDidZoom(scrollView: UIScrollView) {
        
    }
}
